<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品信息管理</title>
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.js"></script>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <style>
        .input-group{
            display: flex;
        }
        .product-img {
            max-width: 100px;
            max-height: 100px;
        }
        .action-btns {
            white-space: nowrap;
        }
        .table{
            width: 100%;
            border-collapse: collapse;
        }
        .table td,th {
            text-align: center;
            vertical-align: middle;
            padding: 8px;
            border: 1px solid #ddd;
        }
        .bottom_{
            display: flex;
            align-items: center;
            justify-content: right;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <h2 class="text-center">商品信息管理</h2>

    <!-- 搜索和添加区域 -->
    <div class="row mb-3">
        <div class="col-md-6">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="搜索商品名称..." id="searchInput">
                <button class="btn btn-outline-secondary" style="margin-left:10px" type="button" id="searchBtn">搜索</button>
                <button class="btn btn-primary" style="margin-left:10px" id="addGoodsBtn">添加商品</button>
                <button class="btn btn-danger"
                        style="margin-left:10px"
                        onclick="delBatch()">批量删除</button>
            </div>
        </div>
    </div>
    <script>
        // 全选
        function selectAll() {
            let chks = document.getElementsByName("chk")
            chks.forEach(function(chk) {
                chk.checked = true;
            });
        }
        // 批量删除
        function delBatch() {
            let chks = document.getElementsByName("chk")
                chks.forEach(function(chk) {
                    if (chk.checked){}
                    console.log(chk.value);
                });
        }
        // function reSelectAll() {
        //     let chks = document.getElementsByName("chk")
        //     chks.forEach(function(chk) {
        //         chk.checked = !chk.checked;
        //     });
        // }
        // 反选
        function reSelectAll() {
            let chkval = document.getElementById("checkvalue")
            if (chkval.checked) {
                let chks = document.getElementsByName("chk")
                chks.forEach(function (chk) {
                    chk.checked = !chk.checked;
                });
            } else {
                    let chks = document.getElementsByName("chk")
                    chks.forEach(function (chk) {
                        chk.checked = !chk.checked;
                    });
                }
            }
        // 取消全选
        function unSelectAll() {
            let chks = document.getElementsByName("chk")
            chks.forEach(function(chk) {
                chk.checked = false;
            });;
        }
    </script>
    <!-- 商品表格 -->
    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover">
            <thead class="table-dark table table-striped">
            <tr>
                <th>
<!--                                    <button onclick="selectAll()">全选</button>-->
<!--                                    <button onclick="reSelectAll()">反选</button>-->
<!--                                    <button onclick="unSelectAll()">取消全选</button>-->
                    <input type="checkbox" value="0" name="" id="checkvalue" onclick="reSelectAll()">
                </th>
                <th>序号</th>
                <th>商品名称</th>
                <th>价格</th>
                <th>描述</th>
                <th>图片</th>
                <th>状态</th>
                <th>商家ID</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="goodsTableBody">
            <!-- 数据将通过JS动态加载 -->
            </tbody>
        </table>
        <tfoot>
            <td colspan="11" style="text-align: center">

            </td>
        </tfoot>
    </div>

    <!-- 分页控件 -->
    <div class="row bottom_">
        <div class="col-md-6">
            <div class="pagination-info" id="paginationInfo">
                显示第 0 至 0 项，共 0 项
            </div>
        </div>
        <div class="col-md-6">
            <nav aria-label="Page navigation" class="float-end" id="pagination">

            </nav>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
<!--                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>-->
            </div>
            <div class="modal-body">
                确定要删除这个商品吗？此操作不可撤销。
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cloce_mode">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确定删除</button>
            </div>
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentPage = 1;
    const pageSize = 5;
    let totalItems = 0;
    let totalPages = 0;
    let currentGoodsId = null; // 用于存储当前要操作的商品ID

    // 页面加载完成后初始化数据
    $(document).ready(function() {
        initData(currentPage, pageSize);

        // 搜索按钮点击事件
        $('#searchBtn').click(function() {
            // currentPage = 1;
            initData(currentPage, pageSize);
        });

        // 添加商品按钮点击事件
        $('#addGoodsBtn').click(function() {
            // 这里可以跳转到添加页面或显示添加模态框
            alert('跳转到添加商品页面');
        });

        // 确认删除按钮点击事件
        $('#confirmDeleteBtn').click(function() {
            if (currentGoodsId) {
                deleteGoods(currentGoodsId);
            }
            $('#deleteConfirmModal').modal('hide');
        });
        $('#cloce_mode').click(function() {
            $('#deleteConfirmModal').modal('hide');
        });
    });

    // 初始化数据
    function initData(page, size) {
        const searchKeyword = $('#searchInput').val().trim();
        $.ajax({
            url: 'allGoods',
            type: "GET",
            data: {
                page: page,
                size: size,
                keyword: searchKeyword
            },
            dataType: 'json',
            beforeSend: function() {
                // 添加加载状态
                $('#goodsTableBody').html('<tr><td colspan="8" class="text-center">加载中...</td></tr>');
            },
            success: function(res) {
                if (res.code === 200) {
                    renderTable(res.data);
                    totalItems = res.total;
                    totalPages = Math.ceil(totalItems / pageSize);

                    updatePaginationInfo(page, size, totalItems);
                    renderPagination(page, Math.ceil(totalItems / size));
                } else {
                    alert('获取数据失败: ' + res.msg);
                }
            },
            error: function(xhr, status, error) {
                alert('请求失败: ' + error);
            },
            complete: function() {
                // 移除加载状态
                $('.loading-indicator').remove();
            }
        });
    }

    // 渲染表格数据
    function renderTable(data) {
        const $tbody = $('#goodsTableBody');
        $tbody.empty();

        if (data.length === 0) {
            $tbody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
            return;
        }

        data.forEach(function(goods) {
            const statusText = goods.state === 0 ? '正常销售' : '不可销售';
            const statusClass = goods.state === 0 ? 'status-0' : 'status-1';

            const row = `
                    <tr>
                        <td>
                            <input type="checkbox" value="${goods.id}" name="chk">
                        </td>
                        <td>${goods.id}</td>
                        <td>${goods.title}</td>
                        <td>¥${goods.price.toFixed(2)}</td>
                        <td>${goods.descr}</td>
                        <td><img src="${goods.img}" alt="商品图片" class="product-img img-thumbnail"></td>
                        <td class="${statusClass}">${statusText}</td>
                        <td>${goods.mid}</td>
                        <td class="action-btns">
                            <button class="btn btn-sm btn-warning edit-btn" data-id="${goods.id}">编辑</button>
                            <button class="btn btn-sm btn-danger delete-btn" data-id="${goods.id}">删除</button>
                        </td>
                    </tr>
                `;

            $tbody.append(row);
        });

        // 绑定编辑和删除按钮事件
        $('.edit-btn').click(function() {
            const goodsId = $(this).data('id');
            editGoods(goodsId);
        });

        $('.delete-btn').click(function() {
            currentGoodsId = $(this).data('id');
            $('#deleteConfirmModal').modal('show');
        });
    }

    // 更新分页信息
    function updatePaginationInfo(page, size, total) {
        const start = (page - 1) * size + 1;
        let end = page * size;
        if (end > total) end = total;

        $('#paginationInfo').text(` ${start} - ${end} ，共 ${total} `);
    }

    // 渲染分页控件
    function renderPagination(page, totalPages) {
        const $pagination = $('#pagination');
        $pagination.empty();

        let paginationHtml = `
        <ul class="pagination">
            <li class="page-item ${page === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="1">首页</a>
            </li>
            <li class="page-item ${page === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${page - 1}">&laquo;</a>
            </li>`;

        const startPage = Math.max(1, page - 2);
        const endPage = Math.min(totalPages, page + 2);

        for (let i = startPage; i <= endPage; i++) {
            paginationHtml += `
            <li class="page-item ${i === page ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>`;
        }

        paginationHtml += `
            <li class="page-item ${page === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${page + 1}">&raquo;</a>
            </li>
            <li class="page-item ${page === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${totalPages}">尾页</a>
            </li>
        </ul>`;

        $pagination.html(paginationHtml);

        // 统一绑定分页事件
        $pagination.off('click', '.page-link').on('click', '.page-link', function(e) {
            e.preventDefault();
            const newPage = parseInt($(this).data('page'));
            if (!isNaN(newPage) && newPage !== currentPage && newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                initData(currentPage, pageSize);
            }
        });
    }


    // 编辑商品
    function editGoods(id) {
        // 这里可以跳转到编辑页面或显示编辑模态框
        window.open("editGoods.html?id=" + id, "_blank");
    }

    // 删除商品
    function deleteGoods(id) {
        $.ajax({
            url: 'deleteGoods',
            type: "POST",
            data: { id: id },
            dataType: 'json',
            success: function(res) {
                if (res.code === 200) {
                    alert(res.msg || '操作成功');
                    initData(currentPage, pageSize); // 刷新数据
                } else {
                    alert('操作失败: ' + (res.msg || '未知错误'));
                }
            },
            error: function(xhr) {
                const res = xhr.responseJSON;
                alert('请求失败: ' + (res ? res.msg : xhr.statusText));
            }
        });
    }
</script>
</body>
</html>